#include <QTimer>
#include <QDebug>
#include "cserialport.h"

CSerialPort::CSerialPort()
{
    m_pPort = new QextSerialPort();
    timer = new QTimer();
    m_PortSet.port = "";
    m_flag = false;
}
CSerialPort::~CSerialPort()
{
    if (timer != NULL)
    {
        timer->stop();
        delete timer;
        timer = NULL;
    }
    if (m_pPort != NULL)
    {
        if (m_pPort->isOpen())
            m_pPort->close();
        delete m_pPort;
        m_pPort = NULL;
    }

    m_PortSet.port = "";
    m_flag =  false;
}
SerialStruct CSerialPort::GetParam()
{
    return m_PortSet;
}

void CSerialPort::SetParam(SerialStruct argPort)
{
    m_PortSet = argPort;
}

bool CSerialPort::OpenCom()
{
    if (!m_PortSet.port.isEmpty())
    {
        m_pPort->setPortName(m_PortSet.port);
        m_pPort->setQueryMode(QextSerialBase::Polling);
        m_pPort->setBaudRate(m_PortSet.baud);
        m_pPort->setDataBits(m_PortSet.dataBits);
        m_pPort->setParity(m_PortSet.parity);
        m_pPort->setStopBits(m_PortSet.stopBits);
        m_pPort->setFlowControl(m_PortSet.flow);
        m_pPort->setTimeout(5);

        if (m_pPort->open(QIODevice::ReadWrite))
        {
            connect(timer, SIGNAL(timeout()), this, SLOT(slotReadData()));
            timer->start(5);
            m_flag = true;
            return true;
        }
    }

    return false;
}

void CSerialPort::CloseCom()
{
    if ((m_pPort!=NULL) && (m_pPort->isOpen()))
    {
        m_pPort->close();
    }
    m_flag = false;
}

bool CSerialPort::IsConnected()
{
    return m_flag;
}

int CSerialPort::SendData(QString data)
{
    if (data.isEmpty())
        return 0;
    return m_pPort->write(data.toAscii());
}
void CSerialPort::slotReadData()
{
    QByteArray data;
    int len = 0;

    len = ReceiveData(data);
    if (len>0)
    {
        emit sigDataRecieve(data.data(), data.size());
    }
}

int CSerialPort::ReceiveData(QByteArray &rdata)
{
    int numBytes = 0;

    numBytes = m_pPort->bytesAvailable();
    if(numBytes > 0)
    {
        if(numBytes > 1024) numBytes = 1024;
        rdata = m_pPort->readAll();
//        for (int i=0; i<numBytes;i++)
//        {
//            qDebug("PORT: %d", (unsigned char)rdata.data()[i]);
//        }
        return numBytes;
    }
    return 0;
}
